package com.dianban.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.dao.FacePayDeviceLogDao;
import com.dianban.entity.FacePayConfig;
import com.dianban.entity.FacePayDeviceLog;
import com.dianban.service.FacePayConfigService;
import com.dianban.service.FacePayDeviceLogService;
import com.dianban.utils.DateUtils;
import com.dianban.utils.HttpUtil;
import com.dianban.utils.RequestTask;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用户业务实现层
 *
 * Created by bysocket on 07/02/2017.
 */
@Service
@Transactional(readOnly = true)
public class FacePayDeviceLogServiceImpl implements FacePayDeviceLogService {

    public static final String changeSwitch = "http://120.24.76.21:8080/iot-admin/app/modbus/changeSwitch";

    @Autowired
    private FacePayDeviceLogDao facePayDeviceLogDao;
    @Autowired
    private FacePayConfigService facePayConfigService;

    public static ExecutorService executorService = Executors.newCachedThreadPool();

    @Override
    public int insert(FacePayDeviceLog facePayDeviceLog) {
        return facePayDeviceLogDao.insert(facePayDeviceLog);
    }

    @Transactional(readOnly = false)
    @Override
    public ResultVo deviceSwitch(Integer status, Long storeId, Integer executeMinute){
        boolean flag = false;
        try {
            Date curDate = new Date();
            // 打开设备
            if(status == 1){
                List<FacePayConfig> facePayConfigList = facePayConfigService.find(20,0,storeId);
                if(!facePayConfigList.isEmpty()){
                    Long id = facePayConfigList.get(0).getId();
                    String name = facePayConfigList.get(0).getName();
                    String value = facePayConfigList.get(0).getValue();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("sn",name);
                    jsonObject.put("address",value);
                    jsonObject.put("switchFlag",true);
                    String result = HttpUtil.doPostByJson(changeSwitch,jsonObject.toJSONString());
                    // 线程池执行打开操作
                    executorService.execute(new RequestTask(changeSwitch, jsonObject.toJSONString()));
                    if(StringUtils.isNotBlank(result)){
                        JSONObject resultJson = JSON.parseObject(result);
                        if(resultJson.get("msg") != null && "success".equals(resultJson.getString("msg"))){
                            facePayConfigService.updateState(id,status,curDate);
                            FacePayDeviceLog facePayDeviceLog = new FacePayDeviceLog();
                            facePayDeviceLog.setSn(name);
                            facePayDeviceLog.setAddress(value);
                            facePayDeviceLog.setStatus(status);
                            facePayDeviceLog.setCreateTime(curDate);
                            facePayDeviceLogDao.insert(facePayDeviceLog);
                            return  ResultVo.success("");
                        }
                        // 统一改成设备未在线
                        String desc = "设备未在线或服务异常,请等候修复!";
                        //return ResultVo.error(ResultCode.ERROR, "打开设备异常："+resultJson.get("msg"));
                        return ResultVo.error(ResultCode.ERROR, desc);
                    }
                    //return ResultVo.error(ResultCode.ERROR, "打开设备没有返回");
                    return ResultVo.error(ResultCode.ERROR, "设备未应答,请等候修复!");
                    // 线程池执行打开操作
                   // executorService.execute(new RequestTask(changeSwitch, jsonObject.toJSONString()));
                }
                //return ResultVo.error(ResultCode.ERROR, "没有找到关闭的设备");
                return ResultVo.error(ResultCode.ERROR, "当前设备正在服务中,请等待服务结束!");
            }else{
                // 关闭设备
                List<FacePayConfig> facePayConfigList = facePayConfigService.find(20,1,storeId);
                for(FacePayConfig facePayConfig : facePayConfigList){
                    Date startTime = facePayConfig.getStartTime();
                    int differMinute = DateUtils.differMinute(curDate,startTime);
                    if(differMinute > executeMinute){
                        Long id = facePayConfig.getId();
                        String name = facePayConfig.getName();
                        String value = facePayConfig.getValue();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("sn",name);
                        jsonObject.put("address",value);
                        jsonObject.put("switchFlag",false);
                        String result = HttpUtil.doPostByJson(changeSwitch,jsonObject.toJSONString());
                        if(StringUtils.isNotBlank(result)){
                            JSONObject resultJson = JSON.parseObject(result);
                            if(resultJson.get("msg") != null && "success".equals(resultJson.getString("msg"))){
                                facePayConfigService.updateState(id,status,null);
                                FacePayDeviceLog facePayDeviceLog = new FacePayDeviceLog();
                                facePayDeviceLog.setSn(name);
                                facePayDeviceLog.setAddress(value);
                                facePayDeviceLog.setStatus(status);
                                facePayDeviceLog.setCreateTime(curDate);
                                facePayDeviceLogDao.insert(facePayDeviceLog);
                            }
                        }
                        // 线程池执行关闭操作
                        executorService.execute(new RequestTask(changeSwitch, jsonObject.toJSONString()));
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "调用设备异常");
        }
        return  ResultVo.success("");
    }
}
